module HelperTools
  def title(content)
  	content_for(:title) { content } unless content.blank?
  end
  
  def javascript(*args)
  	content_for(:head) { javascript_include_tag(*args) }
	end
	
	def stylesheet(*args)
		content_for(:head) { stylesheet_link_tag(*args) }
	end
	
	def description(content)
		content_for(:description) { tag(:meta, :content=>content, :name=>"description") } unless content.blank?
	end
	
	def keywords(content)
		content_for(:keywords) { tag(:meta, :content=>content, :name=>"keywords") } unless content.blank?
	end
	
	def text_teaser(txt, length, more_link = "")
  	return if txt.blank?
		txt = txt.no_html
  	cuted = txt[/(.|\n){0,#{length}}[\w]*/]
		cuted += more_link if(cuted != txt)
		cuted
  end
	
	def anchor_to(name, options={})
	  return if name.blank?
	  options[:name] = name
	  
	  content_tag(:a, '', options)
	end

  def link_by_href(name, options={})
    link_to name, name, options
  end
  
  def link_to_unless_current_span(name, options = {}, html_options = {}, &block)
		link_to_unless_span current_page?(options), name, options, html_options, &block
	end
	
	def link_to_unless_span(condition, name, options = {}, html_options = {}, &block)
		if condition
			if block_given?
				block.arity <= 1 ? yield(name) : yield(name, options, html_options)
			else
			 content_tag(:span, name, html_options)
			end
		else
			link_to(name, options, html_options)
		end
	end
	
	def link_to_if_tag(condition, name, options = {}, html_options = {}, &block)
		tag_name = html_options.delete(:tag) || :span
		if condition
			link_to(name, options, html_options)
		else
			if block_given?
				block.arity <= 1 ? yield(name) : yield(name, options, html_options)
			else
			 content_tag(tag_name, name, html_options)
			end
		end
	end	
	
	def link_to_remote_if(condition, name, options = {}, html_options = nil)
		return name unless condition
		link_to_function(name, remote_function(options), html_options || options.delete(:html))
	end
	
	def submit_image(name, src, options={})
	  html_options = options.dup.symbolize_keys
	  
	  html_options[:name] = name
	  html_options[:src] = src
	  html_options[:type] ||= 'image'
	  
	  tag(:input, html_options)
	end
	
  def submit_image_to_remote(name, value, options = {})
    options[:with] ||= 'Form.serialize(this.form)'
    
    html_options = options.delete(:html) || {}
    html_options[:name] = name
    html_options[:type] ||= 'button'

    onclick = html_options.delete(:onclick) || remote_function(options)
 
    tag(:input, html_options.merge(:value => name, :onclick => onclick))
  end
  
  def locale_image_tag(source, options = {})
    source = "#{I18n.locale}/#{source}"
    image_tag(source, options)
  end
  
  def html_truncate(html, options={})
    content = []
    omission = options[:path].blank? ? '' : 
                content_tag("div", link_to(t('label.read_more'), options[:path]), :class=>"read-more")
    
    if (m = /<hr\s[^>]*class\s*=\s*("|')?cut("|')?[^>]*>/i.match(html))
      content << Nokogiri::HTML(html[0..(m.offset(0)[0]-1)])
      content << omission
    else
      # Does not behave identical to current Rails truncate method i.e. you must pass options as a hash not just values
      # Sample usage: <%= html_truncate(category.description, :length => 120, :omission => "(continued...)" ) -%>...
      previous_tag = ""
      text = []
      
      # get all text (including punctuation) and tags and stick them in a hash
      html.scan(/<\/?[^>]*>|[\w.,;!"'?]+/).each { |t| text << t }
      
      text.each do |str|
        if options[:length] > 0
          if str =~ /<\/?[^>]*>/
            previous_tag = str
            content << str
          else
            content << str
            options[:length] -= str.length
          end
        else
          # now stick the next tag with a </> that matches the previous open tag on the end of the result
          if !previous_tag.blank? && str =~ /<\/([#{previous_tag}]*)>/
            content << str
          else
          end
        end
      end
      
      content << omission
    end
    
    return content.join(" ")
  end
  
  # swf_object
  def swf_object(swf, id, width, height, flash_version, params = {}, vars = {}, create_div = false)
    output = create_div ? "<div id='div_#{id}'>This website requires <a href='http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash&promoid=BIOW' target='_blank'>Flash player</a> #{flash_version} or higher.</div>" : ''
    output << "<script type='text/javascript'>"
    
    arr_params = []
    arr_vars = []
    params.each{|k, v| arr_params << "#{k}:'#{v}'" }
    vars.each{|k, v| arr_vars << "#{k}:'#{v}'" }
    
    output << "var params = {#{arr_params.join(',')}};"
    output << "var attributes = { classid:'clsid:D27CDB6E-AE6D-11cf-96B8-444553540000', id:'#{id}', name:'#{id}' };"
    output << "var flashvars = {#{arr_vars.join(',')}};"
		output << "swfobject.embedSWF('#{swf}', 'div_#{id}', '#{width}', '#{height}', '#{flash_version}', '/swf/expressInstall.swf', flashvars, params, attributes);"
    output << "</script>"
  end
end
